package com.thunbu.lib_common.utils;

import java.io.File;

/**
 * Created by Chaolue.Fan on 2021/5/24
 * 描述:
 */
public class FileUtils {

    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }
    /**
     * 计算CRC16校验码
     *
     * @param bytes
     * @return
     */
    public static  String getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return Integer.toHexString(CRC);
    }

    public static byte [] Str2Hex(String hexStrIn){
        int hexlen = hexStrIn.length()/2;
        byte [] result;
        result = new byte[hexlen];
        for (int i = 0; i < hexlen; i++){
            result[i]=hexStrToByte(hexStrIn.substring(i*2,i*2+2));
        }
        return result;
    }
    static public byte hexStrToByte(String hexbytein){
        return (byte)Integer.parseInt(hexbytein,16);
    }

}
